﻿
using LOLApi.Models;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.RegularExpressions;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Linq;



namespace LOLApi
{
    public static class GetInfo
    {

        private const int MaxRetryCount = 5;
        public static async Task<Summoner?> GetSummonerAsync(HttpClient LcuClient)
        {
            int retryCount = 0;
            while (true)
            {
                try
                {
                    Summoner? result = await LcuClient.GetFromJsonAsync<Summoner>("/lol-summoner/v1/current-summoner");
                    return result;
                }
                catch (Exception ex)
                {
                    retryCount++; // 增加失败计数
                    if (retryCount >= MaxRetryCount)
                    {
                        // 超过最大重试次数，返回 null 或处理其他逻辑
                        return null; // 或者 throw new Exception("请求失败超过最大次数");
                    }
                }
                await Task.Delay(2000);
            }

        }
        public static async Task<bool> TestLoLClientLoadCompelteAsync(HttpClient LcuClient)
        {
            try
            {
                string? result = await LcuClient.GetFromJsonAsync<string>("/lol-gameflow/v1/gameflow-phase");
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        public static async Task<ImageSource> GetAvatar(HttpClient LcuClient, int ProfileIconId)
        {
            byte[] imageData = await LcuClient.GetByteArrayAsync("/lol-game-data/assets/v1/profile-icons/" + ProfileIconId.ToString() + ".jpg");
            using (var stream = new MemoryStream(imageData))
            {
                var bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                bitmap.StreamSource = stream;
                bitmap.EndInit();
                bitmap.Freeze(); // 使其线程安全
                return bitmap;
            }
        }
        public static async Task<Champions[]?> GetOwnedChampions(HttpClient LcuClient)
        {
            Champions[]? result = await LcuClient.GetFromJsonAsync<Champions[]>("/lol-champions/v1/owned-champions-minimal");
            return result;
        }

        public static async Task<ImageSource> GetChampionsImage(HttpClient LcuClient, string imageAddress)
        {
            byte[] imageData = await LcuClient.GetByteArrayAsync(imageAddress);
            using (var stream = new MemoryStream(imageData))
            {
                var bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                bitmap.StreamSource = stream;
                bitmap.EndInit();
                bitmap.Freeze(); // 使其线程安全
                return bitmap;
            }
        }

        public static async Task<Skins[]?> GetOwnedSkins(HttpClient LcuClient, ulong summonerId)
        {
            Skins[]? result = await LcuClient.GetFromJsonAsync<Skins[]>($"/lol-champions/v1/inventories/{summonerId}/skins-minimal ");
            return result;
        }
        public static async Task<SkinsImageAddress?> GetOwnedSkins(HttpClient LcuClient, ulong summonerId, ulong championId, ulong skinId)
        {
            SkinsImageAddress? result = await LcuClient.GetFromJsonAsync<SkinsImageAddress>($"/lol-champions/v1/inventories/{summonerId}/champions/{championId}/skins/{skinId}");
            return result;
        }
        public static async Task<Matches?> GetMatchesAsync(HttpClient LcuClient, string Puuid, int start, int end)
        {
            Matches? result = await LcuClient.GetFromJsonAsync<Matches>($"/lol-match-history/v1/products/lol/{Puuid}/matches?begIndex={start}&endIndex={end}");
            return result;
        }
        public static async Task<ChampionInfo[]?> GetChampionInfos(HttpClient LcuClient)
        {
            ChampionInfo[]? result = await LcuClient.GetFromJsonAsync<ChampionInfo[]>($"/lol-game-data/assets/v1/champion-summary.json");
            return result;
        }

        public static async Task<Rank?> GetRankAsync(HttpClient LcuClient, string Puuid)
        {
            Rank? result = new Rank();
            var response = await LcuClient.SendAsync(new(HttpMethod.Get, $"/lol-ranked/v1/ranked-stats/{Puuid}"));
            string responseBody = await response.Content.ReadAsStringAsync();
            var jsonObject = JToken.Parse(responseBody)["queueMap"];
            if (jsonObject != null) result = jsonObject.ToObject<Rank>();
            return result;
        }
        public static async Task<Summoner?> GetPuuidByName(HttpClient LcuClient, string name)
        {
            Summoner? result = new Summoner();
            string[] gameName = name.Split('#');
            if (gameName.Length == 2)
            {
                result = await LcuClient.GetFromJsonAsync<Summoner>($"/lol-summoner/v1/alias/lookup?gameName={gameName[0]}&tagLine={gameName[1]}");
                return result;
            }
            return null;
        }
        public static async Task<RecordDetail?> GetMathesDetail(HttpClient LcuClient, long? gameId)
        {
            RecordDetail? result = new RecordDetail();
            result = await LcuClient.GetFromJsonAsync<RecordDetail>($"/lol-match-history/v1/games/{gameId}");
            return result;
        }
        public static async Task AutoAcceptGame(HttpClient LcuClient)
        {
            try
            {
                var result = await LcuClient.PostAsync($"/lol-matchmaking/v1/ready-check/accept", null);
                result.EnsureSuccessStatusCode();
            }
            catch (Exception ex)
            {

            }


        }
        public static async Task AutoNextGame(HttpClient LcuClient)
        {
            try
            {
                var result = await LcuClient.PostAsync($"/lol-lobby/v2/play-again", null);
                result.EnsureSuccessStatusCode();
            }
            catch (Exception ex)
            {

            }

        }


    }
}
